package fm.dongman.animefm.view.fragment;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import fm.dongman.animefm.R;
import fm.dongman.animefm.contractlib.IModel;
import fm.dongman.animefm.contractlib.contract.ComicInfoContract;
import fm.dongman.animefm.contractlib.contract.MyContract;
import fm.dongman.animefm.contractlib.model.ScoreModel;
import fm.dongman.animefm.view.activity.SingleActivity;
import fm.dongman.animefm.view.activity.WebVideoActivity;
import fm.dongman.animefm.view.activity.WebViewActivity;
import fm.dongman.animefm.view.activity.WebViewVideoActivity;
import fm.dongman.animefm.view.adapter.ComicRecommendAdapter;
import fm.dongman.animefm.view.adapter.FArticlesLatestAdapter;
import fm.dongman.animefm.view.fragment.SheetListFragment.SheetListSpecialAdapter;
import fm.dongman.animefm.view.transform.GlideRoundTransform;
import fm.dongman.animefm.view.util.ActivityHelper;
import fm.dongman.animefm.view.util.ShareHelper;
import fm.dongman.animefm.view.util.SystemHelper;
import fm.dongman.animefm.view.util.ToastHelper;
import fm.dongman.animefm.view.widget.AnimeDetailsRatingDialog;
import fm.dongman.animefm.view.widget.AnimeWatchSourceFeedbackDialog;
import fm.dongman.animefm.view.widget.ChooseSheetDialog;
import fm.dongman.animefm.view.widget.CircleRatingDisplayView;
import fm.dongman.animefm.view.widget.CommentEditTextDialog;
import fm.dongman.animefm.view.widget.EditTextDialog;
import fm.dongman.animefm.view.widget.MultiStateLayout;
import fm.dongman.modellib.StaticArea.Injection;
import fm.dongman.modellib.model.ComicModel;
import fm.dongman.modellib.model.ComicPictureModel;
import fm.dongman.modellib.model.ComicPlayModel;
import fm.dongman.modellib.model.CommentModel;
import fm.dongman.modellib.model.FeedBackModel;
import fm.dongman.modellib.model.SheetModel;
import fm.dongman.presenterlib.presenter.ComicInfoPresenter;
import fm.dongman.presenterlib.presenter.SheetInfoPresenter;

/**
 * @author alex
 * @description 漫单详情页
 */

public class AnimeDetailsFragment extends BaseFragment implements View.OnClickListener, ComicInfoContract.IComicInfoView {

    private static final String ARG_ANIME_ID = "anime_id";

    //相关番剧、专题、漫单的父容器，没有数据时直接隐藏
    private LinearLayout mLayoutRltComic;
    private LinearLayout mLayoutRltTopic;
    private LinearLayout mLayoutRltSheet;

    //正在加载布局
    private MultiStateLayout mLayoutLoading;

    private List<IModel.IComicModel> mComicList;  //相关番剧
    private ComicRecommendAdapter mComicListAdapter;

    private List<IModel.IArticleModel> mArticleModelList;   //相关专题
    private FArticlesLatestAdapter mArticlesAdapter;

    private List<IModel.ISheetModel> mSheetModelList;   //相关漫单
    private SheetListSpecialAdapter mSheetListAdapter;


    private View mView;
    private ComicInfoContract.IComicInfoPresenter mPresenter;
    private RecyclerView mRvPicture;       //剧照列表
    private RecyclerView mRvWatchSource;    //观看资源列表
    private RecyclerView mRvRecommendAnime;     //相关番剧列表
    private RecyclerView mRvRecommendSheet;     //相关专题列表
    private RecyclerView mRvRecommendArticle;   //相关漫贴列表
    private RecyclerView mRvComment; //评论列表
    private LinearLayout mRvNoCommentLayout;
    private Button mBtnAllComments;   //查看所有评论

    private TextView mTvComment;    //点击评论 按钮
    private TextView mTvWatchAllComments;   //查看所有评论 按钮

    private List<SheetModel> mCollectionSheetList;  //收藏漫单列表

    private Button mBtnRating;      //我要评分 按钮
    private ImageView mIvShare;     //toolbar 分享按钮
    private ImageView mIvMore;      //toolbar 更多按钮
    private Button mBtnAddToSheet;      //加入漫单 按钮
    private AppBarLayout mAppBarLayout;
    private Toolbar mToolbar;
    private CollapsingToolbarLayout mCollapsingToolbarLayout;

    private CircleRatingDisplayView mRatingDisplayView;     //自定义控件，用于显示评分的圆环

    private TextView mTvStory;  //剧情TextVew
    private TextView mTvPaint;  //画风TextVew
    private TextView mTvMusic;  //音乐TextVew
    private TextView mTvPeople; //人设TextVew

    private RatingBar mRbStory;     //显示剧情的RatingBar
    private RatingBar mRbPaint;     //显示画风的RatingBar
    private RatingBar mRbMusic;     //显示音乐的RatingBar
    private RatingBar mRbPeople;    //显示人设的RatingBar

    private TextView mTvRatingScore;    //评分

    private TextView mTvBrowseTime;     //浏览次数
    private ImageView mIvAnimeCover;    //动漫封面
    private TextView mTvAnimeTitle;     //动漫标题
    private TextView mTvAnimeType;    //篇幅
    private TextView mTvAnimeGenre;      //类型
    private TextView mTvAnimeDirector;  //导演
    private TextView mTvAnimeCast;    //作者
    private TextView mTvAnimeCountry;   //公司
    private TextView mTvAnimeSummary;   //动漫简介
    private TextView mTvAnimeSummaryLoadingMore;

    private ComicModel mComicModel;   //当前动漫

    private LinearLayout mLlNoWatchData;

    private LinearLayout mLlWatchSourceContainer;   //用于存放播放源切换按钮的ViewGroup
    private LinearLayout mLlNoPicLayout;    //没有剧照时需要显示的view
    List<ComicPlayModel> mComicPlayModelList;   //所有播放源的数据
    private int mSelectedWatchIndex;    //当前所选中的播放源索引
    private int mComicNum = 0;  //总集数
    private AnimeDetailsWatchSourceAdapter mWatchSourceAdapter;

    //动漫id
    private String mAnimeId;

    public AnimeDetailsFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_anime_details, container, false);
        new ComicInfoPresenter(this, Injection.provideComicInfoRemoteDataSource(getActivity().getApplicationContext()));
        return mView;
    }

    @Override
    public void setPresenter(ComicInfoContract.IComicInfoPresenter presenter) {
        mPresenter = presenter;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mAnimeId = getArguments().getString(ARG_ANIME_ID);
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        mPresenter.getMySheets();
    }

    @Override
    public void initData() {
        initComponents(mView); //初始化控件
        mLayoutLoading.changeState(MultiStateLayout.Companion.getLOADING());
    }

    @Override
    public void bindData() {
        mPresenter.getComicInfo(mAnimeId);
        bindToolbar();
    }

    /**
     * 绑定 Toolbar
     */
    private void bindToolbar() {
        mToolbar.setPadding(0, SystemHelper.INSTANCE.getStatusBarHeight(getActivity()), 0, 0);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityHelper.INSTANCE.backActivity(getActivity());
            }
        });
    }

    @Override
    public void showComicInfo(@NotNull IModel.IComicModel comicInfo) {
        mComicModel = (ComicModel) comicInfo;
        updateDisplayInfo(mComicModel);
        updatePictureInfo(mComicModel);
        updateRatingInfo(mComicModel);
        updateWatchSource(mComicModel);
        mLayoutLoading.changeState(MultiStateLayout.Companion.getSUCCESS());
    }

    /**
     * 更新截图
     */
    private void updatePictureInfo(ComicModel mComicModel) {
        if (mComicModel.getImgList() == null || mComicModel.getImgList().size() <= 0) {
            mLlNoPicLayout.setVisibility(View.VISIBLE);
            mRvPicture.setVisibility(View.GONE);
            return;
        }
        mRvPicture.setAdapter(new AnimeDetailsPictureAdapter(mComicModel, getActivity()));
        mRvPicture.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
    }

    /**
     * 更新动漫显示信息
     */
    private void updateDisplayInfo(ComicModel comicModel) {
        mTvBrowseTime.setText(comicModel.getBrowseCount());
        //加载动漫封面
        Glide.with(getActivity()).load(comicModel.getImgUrl()).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                mIvAnimeCover.setImageBitmap(resource);
                //进行颜色吸取
                Palette.from(resource).generate(new Palette.PaletteAsyncListener() {
                    @Override
                    public void onGenerated(Palette palette) {
                        int defColor = ContextCompat.getColor(getActivity(), R.color.primary);
                        int color = palette.getVibrantColor(defColor);
                        //改变AppBarLayout背景色的过渡动画
                        ObjectAnimator.ofArgb(mAppBarLayout, "backgroundColor", defColor, color)
                                .setDuration(200)
                                .start();
                        mAppBarLayout.setBackgroundColor(color);
                        mRatingDisplayView.setRatingColor(color);
                        mTvAnimeSummaryLoadingMore.setTextColor(color);
                        mCollapsingToolbarLayout.setContentScrimColor(color);
                        mBtnAddToSheet.setBackgroundTintList(new ColorStateList(new int[][]{{0}}, new int[]{color}));
                    }
                });
            }
        });

        mTvAnimeTitle.setText(comicModel.getTitle());
        mTvAnimeType.setText(comicModel.getSubType());
        mTvAnimeGenre.setText(comicModel.getGenre());
        mTvAnimeDirector.setText(comicModel.getDirector());
        mTvAnimeCast.setText(comicModel.getCasts());
        mTvAnimeCountry.setText(comicModel.getCountry());

        //简介长度超过100，精简显示
        String summary = comicModel.getSummary();
        if (summary.length() > 100) {
            summary = summary.substring(0, 100) + "...";
            mTvAnimeSummaryLoadingMore.setVisibility(View.VISIBLE);
        }
        mTvAnimeSummary.setText(summary);

    }

    /**
     * 更新评分信息
     *
     * @param comicModel 动漫
     */
    private void updateRatingInfo(ComicModel comicModel) {
        try {
            mTvStory.setText(comicModel.getStoryScore());
            mRbStory.setRating(Float.parseFloat(comicModel.getStoryScore()) / 2);

            mTvPaint.setText(comicModel.getPictureScore());
            mRbPaint.setRating(Float.parseFloat(comicModel.getPictureScore()) / 2);

            mTvMusic.setText(comicModel.getMusicScore());
            mRbMusic.setRating(Float.parseFloat(comicModel.getMusicScore()) / 2);

            mTvPeople.setText(comicModel.getCharacterScore());
            mRbPeople.setRating(Float.parseFloat(comicModel.getCharacterScore()) / 2);

            mTvRatingScore.setText(comicModel.getRateScore().contains(".") ? comicModel.getRateScore() : comicModel.getRateScore() + ".0");
            mRatingDisplayView.setRating(Float.parseFloat(comicModel.getRateScore()) / 2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新播放列表资源
     */
    private void updateWatchSource(ComicModel comicModel) {
        mComicPlayModelList = comicModel.getPlaylist();

        if (mComicPlayModelList.size() == 0) {
            //列表为空显示无资源提示
            mLlNoWatchData.setVisibility(View.VISIBLE);
            mLlWatchSourceContainer.setVisibility(View.GONE);
            return;
        }

        for (int i = 0; i < mComicPlayModelList.size(); i++) {
            ComicPlayModel playModel = mComicPlayModelList.get(i);
            TextView textView = (TextView) View.inflate(getActivity(), R.layout.item_anime_details_watch_source_btn, null);
            textView.setText(replaceSiteName(playModel.getSource()));
            textView.setTag(i);
            textView.setOnClickListener(this);
            mLlWatchSourceContainer.addView(textView);
        }

        mComicNum = Integer.parseInt(mComicPlayModelList.get(0).getNum());
        changeWatchSourceStateStyle(0);
        isWatchSourceRecyclerViewNeedScroll();

        mWatchSourceAdapter = new AnimeDetailsWatchSourceAdapter(getActivity());
        mRvWatchSource.setAdapter(mWatchSourceAdapter);
        mRvWatchSource.setLayoutManager(new GridLayoutManager(getActivity(), 5, GridLayoutManager.VERTICAL, false));
    }

    /**
     * 根据网站英文名称替换中文名称
     *
     * @param site
     * @return
     */
    private String replaceSiteName(String site) {
        String name = site.toLowerCase();
        if (name.contains("youku")) {
            name = "优酷";
        } else if (site.contains("bilibili")) {
            name = "哔哩哔哩";
        } else if (site.contains("pptv")) {
            name = "PPTV";
        } else if (site.contains("iqiyi")) {
            name = "爱奇艺";
        } else if (site.contains("sohu")) {
            name = "搜狐";
        }
        return name;
    }

    /**
     * 更改播放源按钮选中样式
     *
     * @param position
     */
    private void changeWatchSourceStateStyle(int position) {
        //清除所有按钮样式
        for (int i = 0; i < mLlWatchSourceContainer.getChildCount(); i++) {
            mLlWatchSourceContainer.getChildAt(i).setBackgroundColor(Color.parseColor("#ffffffff"));
            ((TextView) mLlWatchSourceContainer.getChildAt(i)).setTextColor(ContextCompat.getColor(getActivity(), R.color.home_sub_title_color));
        }
        //为当前选中的按钮设置选中样式
        mLlWatchSourceContainer.getChildAt(position).setBackgroundResource(R.drawable.bg_watch_source_selected);
        ((TextView) mLlWatchSourceContainer.getChildAt(position)).setTextColor(Color.parseColor("#ffffff"));
    }

    /**
     * 观看资源列表是否需要滑动
     */
    private void isWatchSourceRecyclerViewNeedScroll() {
        //如果大于4行，则固定高度为160dp，每行固定5列，即除以5
        if (mComicNum / 5 > 4) {
            mRvWatchSource.getLayoutParams().height = (int) TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP, 160, getActivity().getResources().getDisplayMetrics());
            mRvWatchSource.setNestedScrollingEnabled(true);
        }
    }

    @Override
    public void showRelatedComics(@NotNull List<? extends IModel.IComicModel> comics) {
        //相关番剧
        if (!(comics.size() > 0)) {
            mLayoutRltComic.setVisibility(View.GONE);
            return;
        }
        mComicList = (List<IModel.IComicModel>) comics;
        mComicListAdapter = new ComicRecommendAdapter(getActivity(), mComicList);
        mRvRecommendAnime.setAdapter(mComicListAdapter);
        mRvRecommendAnime.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
    }

    @Override
    public void showRelatedArticle(@NotNull List<? extends IModel.IArticleModel> articles) {
        if (!(articles.size() > 0)) {
            mLayoutRltTopic.setVisibility(View.GONE);
            return;
        }
        mArticleModelList = (List<IModel.IArticleModel>) articles;
        mArticlesAdapter = new FArticlesLatestAdapter(mArticleModelList, getActivity());
        mRvRecommendArticle.setAdapter(mArticlesAdapter);
        mRvRecommendArticle.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
    }

    @Override
    public void showRelatedSheets(@NotNull List<? extends IModel.ISheetModel> sheets) {
        if (!(sheets.size() > 0)) {
            mLayoutRltSheet.setVisibility(View.GONE);
            return;
        }
        mSheetModelList = (List<IModel.ISheetModel>) sheets;
        mSheetListAdapter = new SheetListSpecialAdapter(getActivity(), mSheetModelList);
        mRvRecommendSheet.setAdapter(mSheetListAdapter);
        mRvRecommendSheet.setLayoutManager(new GridLayoutManager(getActivity(), 1, GridLayoutManager.HORIZONTAL, false));
    }

    @Override
    public void showJoinSheetSucceed() {
        ToastHelper.getInstance(getActivity()).showSucceed("加入漫单成功");
    }

    @Override
    public void showJoinSheetFailed() {
        ToastHelper.getInstance(getActivity()).showError("加入漫单失败");
    }

    @Override
    public void showFollowSucceed() {
        ToastHelper.getInstance(getActivity()).showSucceed("关注成功");
    }

    @Override
    public void showFollowFailed() {
        ToastHelper.getInstance(getActivity()).showError("关注失败");
    }

    @Override
    public void showScoreSucceed(@NotNull ScoreModel score) {
        mTvStory.setText(score.getPlot());
        mTvPaint.setText(score.getStyle());
        mTvMusic.setText(score.getMusic());
        mTvPeople.setText(score.getPlot());

        ToastHelper.getInstance(getActivity()).showSucceed("评分成功");
    }

    @Override
    public void showScoreFailed() {
        ToastHelper.getInstance(getActivity()).showError("评分失败");
    }

    @Override
    public void showMySheets(@NotNull List<? extends IModel.ISheetModel> sheets) {
        mCollectionSheetList = (List<SheetModel>) sheets;
    }

    @Override
    public void showGetMySheetsFailed() {
//        Toast.makeText(getActivity(), "获取漫单失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @NotNull
    @Override
    public Context getViewContext() {
        return getActivity();
    }

    @Override
    public void showNoNetwork() {
        mLayoutLoading.changeState(MultiStateLayout.Companion.getNET_ERROR());
    }

    @Override
    public void showRefreshFailed() {
        mLayoutLoading.changeState(MultiStateLayout.Companion.getEMPTY());
        ToastHelper.getInstance(getActivity()).showError("漫单详情" + getString(R.string.str_refresh_failed));
    }

    /**
     * 用于实例化AnimeDetailsFragment
     *
     * @param animeId 动漫ID
     * @return 返回一个AnimeDetailsFragment实例
     */

    public static AnimeDetailsFragment getInstance(String animeId) {
        AnimeDetailsFragment fragment = new AnimeDetailsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_ANIME_ID, animeId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onClick(View v) {

        //切换播放源，v.getTag 能获取当前点击position
        if (v.getTag() != null) {
            try {
                mSelectedWatchIndex = (int) v.getTag();     //设置当前源的索引
                changeWatchSourceStateStyle(mSelectedWatchIndex);
                mComicNum = Integer.parseInt(mComicPlayModelList.get(mSelectedWatchIndex).getNum());  //更新总集数
                mWatchSourceAdapter.notifyDataSetChanged();     //通知adapter更新
                ToastHelper.getInstance(getActivity())
                        .showSucceed("当前播放源切换至"
                                + mComicPlayModelList.get(mSelectedWatchIndex).getSource());
                return;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        switch (v.getId()) {
            //toolbar 更多
            case R.id.mIvAnimeDetailsMore:
                PopupMenu popupMenu = new PopupMenu(getActivity(), v);
                popupMenu.inflate(R.menu.menu_anime_details_more);
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            //资源反馈
                            case R.id.comicFeedback:
                                new AnimeWatchSourceFeedbackDialog.Builder(getActivity()).setOnFeedbackListener(new AnimeWatchSourceFeedbackDialog.Builder.OnFeedBackListener() {

                                    @Override
                                    public void onCommit(Dialog dialog, int currentType, String content) {
                                        //反馈相关信息
                                        FeedBackModel feedBackModel = new FeedBackModel();
                                        feedBackModel.setType(currentType);
                                        feedBackModel.setSubjectId(mAnimeId);
                                        feedBackModel.setContent(content);
                                        //发送反馈
                                        mPresenter.sendFeedback(mAnimeId, feedBackModel);
                                        dialog.dismiss();
                                    }

                                    @Override
                                    public void onCancel(Dialog dialog) {
                                        dialog.dismiss();
                                    }
                                }).setTypesAndId(
                                        //类型 取值：0:视频播放；1:评论相关；2:按钮/链接；3:登录相关；4:图片相关；5:动漫信息；6:个人账户；7:其他；
                                        new String[]{"视频播放", "图片相关", "动漫信息", "其他"},
                                        new int[]{FeedBackModel.TYPE_VIDEO, FeedBackModel.TYPE_PIC, FeedBackModel.TYPE_COMMIC_INFO, FeedBackModel.TYPE_OTHER}
                                ).build().show();
                                break;
                        }
                        return true;
                    }
                });
                popupMenu.show();
                break;

            //我要评分
            case R.id.mBtnAnimeDetailsRating:
                new AnimeDetailsRatingDialog.Builder(getActivity())
                        .setOnRatingCommitListenr(new AnimeDetailsRatingDialog.Builder.OnRatingCommitListener() {
                            @Override
                            public void onCommit(Dialog dialog, float storyScore, float paintScore, float musicScore, float peopleScore) {
                                Toast.makeText(getActivity(), "剧情：" + storyScore + "--画风：" + paintScore + "--音乐：" + musicScore + "--人设：" + peopleScore, Toast.LENGTH_SHORT).show();
                                ScoreModel scoreModel = new ScoreModel();
                                scoreModel.setPlot((int) (storyScore * 2));
                                scoreModel.setStyle((int) (paintScore * 2));
                                scoreModel.setCharacters((int) (peopleScore * 2));
                                mPresenter.scoreComic(scoreModel);
                                dialog.dismiss();
                            }
                        })
                        .build()
                        .show();
                break;

            // toolbar 分享
            case R.id.mIvAnimeDetailsShare:
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, ShareHelper.generateShareText(mComicModel.getTitle(), mAnimeId, ShareHelper.TYPE_COMIC));
                startActivity(intent);
                break;

            //添加到漫单
            case R.id.mBtnAnimeDetailsAddToSheet:

                //没登陆跳转到登陆
                if (isNotLoginAndGoLogin()) return;
                //没有漫单数据，可能是session key失效所致
                if (mCollectionSheetList == null) {
                    ToastHelper.getInstance(getActivity()).showError("无法获取漫单，请尝试退出账号重新登录");
                    return;
                }
                new ChooseSheetDialog.Builder(getActivity())
                        .setChooseSheetListener(new ChooseSheetDialog.Builder.ChooseSheetListener() {
                            @Override
                            public void onCreateNewSheet(Dialog dialog) {
                                dialog.dismiss();
                                Intent intent = new Intent(getActivity(), SingleActivity.class);
                                intent.putExtra(SingleActivity.Companion.getEXTRA_NAME(), SingleActivity.Companion.getINTENT_EXTRA_CREATE_OR_EDIT_SHEET());
                                ActivityHelper.INSTANCE.startActivity(getActivity(), intent);
                            }

                            @Override
                            public void onSheetItemClick(String sheetId, Dialog dialog) {
                                mPresenter.joinSheet(sheetId);
                                dialog.dismiss();
                            }
                        }).setSheetList(mCollectionSheetList).build().show();
                break;

            //我要评论
            case R.id.mTvAnimedetailsComment:
                if (isNotLoginAndGoLogin()) return;
                new CommentEditTextDialog.Builder(getActivity())
                        .setTitle("评论:" + mComicModel.getTitle())
                        .setCommentType(CommentModel.TYPE_SUBJECT)
                        .setSubjectId(mAnimeId)
                        .setOnButtonClickListenr(new CommentEditTextDialog.Builder.OnButtonClickListener() {
                            @Override
                            public void onCommit(String inputContent) {

                            }

                            @Override
                            public void onCanceled() {

                            }

                            @Override
                            public void onCommitSucceed() {
                                mPresenter.getComicInfo(mAnimeId);
                            }

                            @Override
                            public void onCommitFailed() {

                            }
                        })
                        .build().show();
                break;

            //查看所有评论
            case R.id.mBtnAnimeDetailsMoreCommments:
            case R.id.mTvAnimedetailsWatchAllComments:
                Intent i = new Intent(getActivity(), SingleActivity.class);
                i.putExtra(SingleActivity.Companion.getEXTRA_NAME(), SingleActivity.Companion.getINTENT_EXTRA_COMMENT_LIST());
                i.putExtra(SingleActivity.Companion.getBUNDLE_EXTRA_KEY_TYPE(), CommentListFragment.Companion.getTYPE_COMIC());
                i.putExtra(SingleActivity.Companion.getBUNDLE_EXTRA_KEY_ID(), mComicModel.getId());
                ActivityHelper.INSTANCE.startActivity(getActivity(), i);
                break;

            //加载完整的简介
            case R.id.mTvAnimeDetailsDescriptionLoadingMore:
                mTvAnimeSummary.setText(mComicModel.getSummary());
                mTvAnimeSummaryLoadingMore.setVisibility(View.GONE);
                break;
        }
    }

    private boolean isNotLoginAndGoLogin() {
        if (MyContract.Companion.getUSER_ID() == null) {
            ToastHelper.getInstance(getActivity()).showError("尚未登录");
            Intent i = new Intent(getActivity(), SingleActivity.class);
            i.putExtra(SingleActivity.Companion.getEXTRA_NAME(), SingleActivity.Companion.getINTENT_EXTRA_LOGIN());
            ActivityHelper.INSTANCE.startActivity(getActivity(), i);
            return true;
        }
        return false;
    }

    /**
     * 初始化控件&注册监听
     *
     * @param layoutView fragment布局View
     */
    private void initComponents(View layoutView) {
        mLlWatchSourceContainer = (LinearLayout) layoutView.findViewById(R.id.mLlAnimeDetailsWatchSource);
        mLlNoWatchData = (LinearLayout) layoutView.findViewById(R.id.mLlAnimeDetailsNoWatchSource);
        mLlNoPicLayout = (LinearLayout) layoutView.findViewById(R.id.mLlAnimeDetailsNoPicSource);

        mRvNoCommentLayout = (LinearLayout) layoutView.findViewById(R.id.mLlAnimeDetailsNoComments);

        mLayoutLoading = (MultiStateLayout) layoutView.findViewById(R.id.mAnimeDetailsMultiStateLayout);

        mLayoutRltComic = (LinearLayout) layoutView.findViewById(R.id.mLlAnimeDetailsRelativeAnimeContainer);
        mLayoutRltTopic = (LinearLayout) layoutView.findViewById(R.id.mLlAnimeDetailsRelativeTopicContainer);
        mLayoutRltSheet = (LinearLayout) layoutView.findViewById(R.id.mLlAnimeDetailsRelativeSheetContainer);

        mRvComment = (RecyclerView) layoutView.findViewById(R.id.mRvAnimeDetailsComments);
        mBtnAllComments = (Button) layoutView.findViewById(R.id.mBtnAnimeDetailsMoreCommments);
        mBtnAllComments.setOnClickListener(this);

        mAppBarLayout = (AppBarLayout) layoutView.findViewById(R.id.mAbAnimeDetails);
        mToolbar = (Toolbar) layoutView.findViewById(R.id.mTbAnimeDetails);
        mCollapsingToolbarLayout = (CollapsingToolbarLayout) layoutView.findViewById(R.id.mCtbLayoutAnimeDetails);
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//                if (verticalOffset == 0) {
//                    mToolbar.setTitle(getResources().getText(R.string.str_back));
//                } else if (verticalOffset == -appBarLayout.getTotalScrollRange()) {
//                    mToolbar.setTitle(mComicModel.getTitle());
//                }
                // 注意：这里多次调用该回调方法，应该减少赋值次数
                if (verticalOffset == 0 && !mToolbar.getTitle().equals(getResources().getText(R.string.str_back))){
                    mToolbar.setTitle(getResources().getText(R.string.str_back));
                } else if (verticalOffset != 0 && mToolbar.getTitle().equals(getResources().getText(R.string.str_back))){
                    mToolbar.setTitle(mComicModel.getTitle());
                }
            }
        });
        mRvPicture = (RecyclerView) layoutView.findViewById(R.id.mRvAnimeDetailsPicture);
        mRvWatchSource = (RecyclerView) layoutView.findViewById(R.id.mRvAnimeDetailsWatchSource);
        mRvRecommendAnime = (RecyclerView) layoutView.findViewById(R.id.mRvAnimeDetailsRecommendAnime);
        mRvRecommendSheet = (RecyclerView) layoutView.findViewById(R.id.mRvAnimeDetailsRecommendSheet);
        mRvRecommendArticle = (RecyclerView) layoutView.findViewById(R.id.mRvAnimeDetailsRecommendArticle);

        mTvComment = (TextView) layoutView.findViewById(R.id.mTvAnimedetailsComment);
        mTvComment.setOnClickListener(this);
        mTvWatchAllComments = (TextView) layoutView.findViewById(R.id.mTvAnimedetailsWatchAllComments);
        mTvWatchAllComments.setOnClickListener(this);

        mBtnRating = (Button) layoutView.findViewById(R.id.mBtnAnimeDetailsRating);
        mBtnRating.setOnClickListener(this);

        mIvShare = (ImageView) layoutView.findViewById(R.id.mIvAnimeDetailsShare);
        mIvShare.setOnClickListener(this);

        mIvMore = (ImageView) layoutView.findViewById(R.id.mIvAnimeDetailsMore);
        mIvMore.setOnClickListener(this);

        mBtnAddToSheet = (Button) layoutView.findViewById(R.id.mBtnAnimeDetailsAddToSheet);
        mBtnAddToSheet.setOnClickListener(this);

        mTvStory = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsRatingStoryScore);
        mTvPaint = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsRatingPaintScore);
        mTvMusic = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsRatingMusicScore);
        mTvPeople = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsRatingPeopleScore);

        mRbStory = (RatingBar) layoutView.findViewById(R.id.mRbStory);
        mRbPaint = (RatingBar) layoutView.findViewById(R.id.mRbPaint);
        mRbMusic = (RatingBar) layoutView.findViewById(R.id.mRbMusic);
        mRbPeople = (RatingBar) layoutView.findViewById(R.id.mRbPeople);

        mTvBrowseTime = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsBrowseTime);
        mIvAnimeCover = (ImageView) layoutView.findViewById(R.id.mIvAnimeDetailsCover);
        mTvAnimeTitle = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsTitle);
        mTvAnimeType = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsLength);
        mTvAnimeGenre = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsType);
        mTvAnimeDirector = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsDirector);
        mTvAnimeCast = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsCast);
        mTvAnimeCountry = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsCountry);

        mTvAnimeSummary = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsDescription);
        mTvAnimeSummaryLoadingMore = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsDescriptionLoadingMore);
        mTvAnimeSummaryLoadingMore.setOnClickListener(this);

        mRatingDisplayView = (CircleRatingDisplayView) layoutView.findViewById(R.id.circleRatingDisplayView);

        mTvRatingScore = (TextView) layoutView.findViewById(R.id.mTvAnimeDetailsRatingNum);
    }

    @Override
    public void showRelatedComments(@NotNull List<? extends IModel.ICommentModel> comments) {
        if (comments.size() == 0) {
            mRvNoCommentLayout.setVisibility(View.VISIBLE);
            mBtnAllComments.setVisibility(View.GONE);
            return;
        }
        mRvComment.setAdapter(new ReviewCommentAdapter(getActivity(), (List<CommentModel>) comments));
        mRvComment.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
    }

    @Override
    public void showFeedbackState(boolean b) {
        ToastHelper.getInstance(getActivity()).showWarn("反馈" + (b ? "成功" : "失败"));
    }

    @Override
    public void showUpdateStillsState(boolean b) {
        ToastHelper.getInstance(getActivity()).showWarn("上传" + (b ? "成功" : "失败"));
    }

    private class ReviewCommentAdapter extends RecyclerView.Adapter<ReviewCommentAdapter.Holder> {

        private List<CommentModel> mModelList;
        private Context mContext;

        ReviewCommentAdapter(Context context, List<CommentModel> models) {
            mContext = context;
            mModelList = models;
        }

        @Override
        public ReviewCommentAdapter.Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new Holder(View.inflate(mContext, R.layout.item_anime_details_review_comment, null));
        }

        @Override
        public void onBindViewHolder(ReviewCommentAdapter.Holder holder, int position) {
            CommentModel comment = mModelList.get(position);
            Glide.with(mContext)
                    .load(comment.getUser().getAvatarUrl())
                    .bitmapTransform(new CenterCrop(mContext), new GlideRoundTransform(mContext, 10))
                    .into(holder.mAvatar);
            holder.mUser.setText(comment.getUser().getUserName());
            holder.mContent.setText(comment.getContent());
        }

        @Override
        public int getItemCount() {
            return mModelList.size();
        }

        class Holder extends RecyclerView.ViewHolder {
            ImageView mAvatar;
            TextView mUser;
            TextView mContent;

            Holder(View itemView) {
                super(itemView);
                mAvatar = (ImageView) itemView.findViewById(R.id.mIvCommentAvatar);
                mUser = (TextView) itemView.findViewById(R.id.mIvCommentUser);
                mContent = (TextView) itemView.findViewById(R.id.mIvCommentContent);
            }
        }
    }

    /**
     * Created by alex on 2017/10/17.
     *
     * @description 动漫详情页下剧照列表adapter
     */

    private class AnimeDetailsPictureAdapter extends RecyclerView.Adapter<AnimeDetailsPictureAdapter.ViewHolder> {

        private List<ComicPictureModel> mComicPictureModels;
        private Context mContext;

        AnimeDetailsPictureAdapter(ComicModel comicModel, Context context) {
            mComicPictureModels = comicModel.getImgList();
            mContext = context;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(View.inflate(mContext, R.layout.item_anime_details_picture, null));
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            Glide.with(getActivity())
                    .load(mComicPictureModels.get(position).getImg())
                    .bitmapTransform(new CenterCrop(mContext), new GlideRoundTransform(mContext, 2))
                    .placeholder(R.mipmap.placeholder_landscape)
                    .into(holder.mPic);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog dialog = new AlertDialog.Builder(mContext, R.style.CustomDialog).create();
                    View dialogView = View.inflate(mContext, R.layout.dialog_show_picture, null);
                    ImageView imageView = (ImageView) dialogView.findViewById(R.id.mIvPic);
                    Glide.with(mContext).load(mComicPictureModels.get(holder.getAdapterPosition()).getImg())
                            .placeholder(R.mipmap.placeholder_landscape)
                            .into(imageView);
                    dialog.show();
                    dialog.setContentView(dialogView);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mComicPictureModels.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            ImageView mPic;

            public ViewHolder(View itemView) {
                super(itemView);
                mPic = (ImageView) itemView.findViewById(R.id.mIvAnimeDetailsPictureList);
            }
        }

    }

    /**
     * Created by alex on 2017/10/17.
     *
     * @description 动漫详情页 相关动漫资源adapter
     */

    public class AnimeDetailsWatchSourceAdapter extends RecyclerView.Adapter<AnimeDetailsWatchSourceAdapter.ViewHolder> {
        private Context mContext;

        AnimeDetailsWatchSourceAdapter(Context context) {
            mContext = context;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(View.inflate(mContext, R.layout.item_anime_details_watch_source, null));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            holder.mWatchTitle.setText("第" + (position + 1) + "集");
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //根据当前选中播放源的索引来获取播放前缀地址，拼接当前点中的集数，即播放地址
                    String playUrl = mComicPlayModelList.get(mSelectedWatchIndex).getDomain() + (holder.getAdapterPosition() + 1);
//                    Intent intent = new Intent(getActivity(), WebVideoActivity.class);
//                    intent.putExtra(WebVideoActivity.Companion.getBUNDLE_KEY(), playUrl);
//                    ActivityHelper.INSTANCE.startActivity(getActivity(), intent);
//                    Log.e("url",playUrl);
                    ActivityHelper.INSTANCE.startActivity(getActivity(), WebViewVideoActivity.getIntent(getActivity(),playUrl));
                }
            });
        }

        @Override
        public int getItemCount() {
            //数量依据当前动漫的集数
            return mComicNum;
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView mWatchTitle;

            public ViewHolder(View itemView) {
                super(itemView);
                mWatchTitle = (TextView) itemView.findViewById(R.id.mTvanimeDetailsWatchItem);
            }
        }
    }
}
